import pdb, os, time, requests, base64, json
import re
import datetime
import logging, random
from conf.sysConfig import config
from pprint import pprint

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
serverIP = config["serverIP"]
serverPort = config["serverPort"]
serverRegUrl = config["serverRegUrl"]
serverCheckUrl = config["serverCheckUrl"]
serverUpdateUrl = config["serverUpdateUrl"]
serverSearchUrl = config["serverSearchUrl"]
serverRegister = config["serverRegister"]
serviceDocker = config["serviceDocker"]


def serviceRegisterCheck():
    # pdb.set_trace()
    msg = requests.get(serverIP + ":" + serverPort + serverCheckUrl.format(serverRegister['serviceName']))
    data = json.loads(msg.text)
    if data['resp_code'] == 0:
        userData = data["datas"]
        if userData:
            print("服务英文名称被占用！")
        else:
            print("服务英文名称未被占用！")
        # pprint(userData)
        return userData
    else:
        pass


def serviceRegister():
    body = json.dumps(serverRegister, ensure_ascii=False).encode('utf-8')
    headers = {
        'Content-Type': "application/json;charset=UTF-8",
    }
    pprint(body)
    msg = requests.post(
        serverIP + ":" + serverPort + serverRegUrl,
        data=body,
        headers=headers
    )
    # logger_request.info(msg.text)
    data = json.loads(msg.text)
    userData = False
    if data['resp_code'] == 0:
        userData = data["datas"]
    return userData


def serviceUpdate():
    body = json.dumps(serverRegister, ensure_ascii=False).encode('utf-8')

    headers = {
        'Content-Type': "application/json;charset=UTF-8",
    }
    msg = requests.post(
        serverIP + ":" + serverPort + serverUpdateUrl,
        data=body,
        headers=headers
    )
    # logger_request.info(msg.text)
    data = json.loads(msg.text)
    userData = False
    if data['resp_code'] == 0:
        userData = data["datas"]
    return userData


def serverSearch():
    body = {
        "interfaceContract": serviceDocker
    }
    msg = requests.get(
        serverIP + ":" + serverPort + serverSearchUrl.format(serviceDocker),
        # data=body
        # headers=headers
    )
    # logger_request.info(msg.text)
    data = json.loads(msg.text)
    pprint(data)
    userData = False
    if data['resp_code'] == 0:
        userData = data["datas"]
    return userData


if __name__ == '__main__':
    # serviceRegisterCheck()
    serviceRegister()
    # serviceUpdate()
    # serverSearch()
